@{
    ViewData["Title"] = "新增BOM";
}

<link href="~/css/site.css" rel="stylesheet" />
<link href="~/layui/css/layui.css" rel="stylesheet" />

<div style="padding: 20px;">
    <h3><i class="layui-icon layui-icon-add-1"></i> 新增BOM</h3>
    
    <!-- 基础信息 -->
    <div class="layui-card" style="margin-top:10px;">
        <div class="layui-card-header">基础信息</div>
        <div class="layui-card-body">
            <form class="layui-form" lay-filter="bom-form" action="">
                <div class="layui-row layui-col-space20">
                    <div class="layui-col-md4">
                        <div class="layui-form-item">
                            <label class="layui-form-label">BOM编号</label>
                            <div class="layui-input-inline" style="width: 200px;">
                                <input type="text" name="bomCode" id="bomCode" placeholder="系统自动生成" autocomplete="off" class="layui-input" lay-verify="required" readonly>
                            </div>
                            <div class="layui-input-inline" style="width: 80px;">
                                <button type="button" class="layui-btn layui-btn-sm" onclick="generateBomCode()">生成编号</button>
                            </div>
                        </div>
                    </div>
                    <div class="layui-col-md4">
                        <div class="layui-form-item">
                            <label class="layui-form-label">BOM主题</label>
                            <div class="layui-input-inline" style="width: 200px;">
                                <input type="text" name="bomTitle" placeholder="请输入BOM主题" autocomplete="off" class="layui-input" lay-verify="required">
                            </div>
                        </div>
                    </div>
                    <div class="layui-col-md4">
                        <div class="layui-form-item">
                            <label class="layui-form-label">版本</label>
                            <div class="layui-input-inline" style="width: 200px;">
                                <input type="text" name="version" placeholder="请输入版本" autocomplete="off" class="layui-input" lay-verify="required">
                            </div>
                        </div>
                    </div>
                </div>

                <div class="layui-row layui-col-space20">
                    <div class="layui-col-md4">
                        <div class="layui-form-item">
                            <label class="layui-form-label">成品名称</label>
                            <div class="layui-input-inline" style="width: 200px;">
                                <input type="text" name="productsName" placeholder="请输入成品名称" autocomplete="off" class="layui-input" lay-verify="required">
                            </div>
                        </div>
                    </div>
                    <div class="layui-col-md4">
                        <div class="layui-form-item">
                            <label class="layui-form-label">产品编号</label>
                            <div class="layui-input-inline" style="width: 200px;">
                                <input type="text" name="productsCode" placeholder="请输入产品编号" autocomplete="off" class="layui-input" lay-verify="required">
                            </div>
                        </div>
                    </div>
                    <div class="layui-col-md4">
                        <div class="layui-form-item">
                            <label class="layui-form-label">规格型号</label>
                            <div class="layui-input-inline" style="width: 200px;">
                                <input type="text" name="productsModel" placeholder="请输入规格型号" autocomplete="off" class="layui-input" lay-verify="required">
                            </div>
                        </div>
                    </div>
                </div>

                <div class="layui-row layui-col-space20">
                    <div class="layui-col-md4">
                        <div class="layui-form-item">
                            <label class="layui-form-label">单位</label>
                            <div class="layui-input-inline" style="width: 200px;">
                                <input type="text" name="productsUnit" placeholder="请输入单位" autocomplete="off" class="layui-input" lay-verify="required">
                            </div>
                        </div>
                    </div>
                    <div class="layui-col-md4">
                        <div class="layui-form-item">
                            <label class="layui-form-label">品牌</label>
                            <div class="layui-input-inline" style="width: 200px;">
                                <input type="text" name="brand" placeholder="请输入品牌" autocomplete="off" class="layui-input">
                            </div>
                        </div>
                    </div>
                    <div class="layui-col-md4">
                        <div class="layui-form-item">
                            <label class="layui-form-label">日产量</label>
                            <div class="layui-input-inline" style="width: 200px;">
                                <input type="number" name="output" placeholder="请输入日产量" autocomplete="off" class="layui-input" min="0" value="0">
                            </div>
                        </div>
                    </div>
                </div>

                <div class="layui-row layui-col-space20">
                    <div class="layui-col-md4">
                        <div class="layui-form-item">
                            <label class="layui-form-label">是否默认版本</label>
                            <div class="layui-input-inline" style="width: 200px;">
                                <input type="checkbox" name="status" lay-skin="primary" title="设为默认版本" checked>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="layui-form-item layui-form-text">
                    <label class="layui-form-label">备注</label>
                    <div class="layui-input-block">
                        <textarea name="desc" placeholder="请输入备注" class="layui-textarea"></textarea>
                    </div>
                </div>
            </form>
        </div>
    </div>

    <!-- BOM配件 -->
    <div class="layui-card" style="margin-top:10px;">
        <div class="layui-card-header">BOM配件</div>
        <div class="layui-card-body">
            <div class="layui-btn-group" style="margin-bottom:10px;">
                <button type="button" class="layui-btn layui-btn-sm" id="btnAddGoods">添加</button>
                <button type="button" class="layui-btn layui-btn-sm layui-btn-danger" id="btnRemoveGoods">移除</button>
            </div>

            <table class="layui-table" lay-size="sm">
                <thead>
                    <tr>
                        <th style="width:50px;"><input type="checkbox" lay-skin="primary" lay-filter="chkAllGoods"></th>
                        <th style="width:60px;">序号</th>
                        <th style="width:120px;">物品编号</th>
                        <th style="width:180px;">物品名称</th>
                        <th style="width:120px;">规格型号</th>
                        <th style="width:80px;">单位</th>
                        <th style="width:120px;">配件数量</th>
                        <th style="width:100px;">损耗率</th>
                        <th style="width:120px;">操作</th>
                    </tr>
                </thead>
                <tbody id="goodsBody">
                    <tr><td colspan="9" style="text-align:center;color:#999;">暂无数据</td></tr>
                </tbody>
            </table>
            <input type="hidden" id="goodsIdsInput" name="goodsIds" value="[]" />
        </div>
    </div>

    <!-- 工艺流程 -->
    <div class="layui-card" style="margin-top:10px;">
        <div class="layui-card-header">工艺流程</div>
        <div class="layui-card-body">
            <div class="layui-btn-group" style="margin-bottom:10px;">
                <button type="button" class="layui-btn layui-btn-sm" id="btnAddFlow">添加</button>
                <button type="button" class="layui-btn layui-btn-sm layui-btn-danger" id="btnRemoveFlow">移除</button>
            </div>

            <table class="layui-table" lay-size="sm">
                <thead>
                    <tr>
                        <th style="width:50px;"><input type="checkbox" lay-skin="primary" lay-filter="chkAllFlow"></th>
                        <th style="width:60px;">序号</th>
                        <th style="width:120px;">工艺流程编号</th>
                        <th style="width:180px;">工艺流程名称</th>
                        <th style="width:100px;">工序数量</th>
                        <th style="width:120px;">备注</th>
                        <th style="width:120px;">操作</th>
                    </tr>
                </thead>
                <tbody id="flowBody">
                    <tr><td colspan="7" style="text-align:center;color:#999;">暂无数据</td></tr>
                </tbody>
            </table>
            <input type="hidden" id="flowIdsInput" name="flowIds" value="[]" />
        </div>
    </div>

    <div class="layui-form-item" style="text-align:right;margin-top:20px;">
        <button class="layui-btn layui-btn-primary" id="btnReset" type="button">重置</button>
        <button class="layui-btn layui-btn-primary" id="btnCancel" type="button">关闭</button>
        <button class="layui-btn" id="btnSave" type="button">确定</button>
    </div>
</div>

<script src="~/lib/jquery/dist/jquery.js"></script>
<script src="~/layui/layui.js"></script>

<script>
    layui.use(['form', 'layer'], function () {
        var layer = layui.layer, form = layui.form;
        
        // 用于存放被选择的数据ID集合
        var goodsIds = [];
        var flowIds = [];

        function updateGoodsIdsInput() {
            $('#goodsIdsInput').val(JSON.stringify(goodsIds));
        }

        function updateFlowIdsInput() {
            $('#flowIdsInput').val(JSON.stringify(flowIds));
        }

        // 页面加载完成后自动生成编号
        $(document).ready(function() {
            generateBomCode();
        });

        // 自动生成BOM编号
        function generateBomCode() {
            var currentDate = new Date();
            var year = currentDate.getFullYear();
            var month = (currentDate.getMonth() + 1).toString().padStart(2, '0');
            var day = currentDate.getDate().toString().padStart(2, '0');
            var sequence = (Math.floor(Math.random() * 9000) + 1000).toString(); // 生成4位随机序号
            var bomCode = 'B' + year + month + day + sequence;
            $('#bomCode').val(bomCode);
        }

        // 点击"确定"按钮提交表单
        $('#btnSave').on('click', function () {
            // 先验证表单
            if (validateForm()) {
                // 显示确认对话框
                layer.confirm('确定要提交BOM数据吗？', {
                    icon: 3,
                    title: '确认提交',
                    btn: ['确定提交', '取消']
                }, function(index) {
                    submitForm();
                    layer.close(index);
                });
            }
        });

        // 点击"重置"按钮
        $('#btnReset').on('click', function () {
            layer.confirm('确定要重置表单吗？所有已填写的数据将丢失。', {
                icon: 3,
                title: '确认重置'
            }, function(index) {
                resetForm();
                layer.close(index);
            });
        });

        // 点击"关闭"按钮
        $('#btnCancel').on('click', function () {
            if (window.parent && window.parent.loadPage) {
                window.parent.loadPage('/Bom/BomList', 'BOM管理');
            } else {
                location.href = '/Bom/BomList';
            }
        });

        // 添加表单重置功能
        function resetForm() {
            // 重置基础信息
            $('form[lay-filter="bom-form"]')[0].reset();
            $('input[name="status"]').prop('checked', true);
            $('input[name="output"]').val('0');
            
            // 清空配件和工艺流程表格
            $('#goodsBody').html('<tr><td colspan="9" style="text-align:center;color:#999;">暂无数据</td></tr>');
            $('#flowBody').html('<tr><td colspan="7" style="text-align:center;color:#999;">暂无数据</td></tr>');
            
            // 重置ID数组
            goodsIds = [];
            flowIds = [];
            updateGoodsIdsInput();
            updateFlowIdsInput();
            
            // 重新渲染表单
            layui.form.render();
            
            layer.msg('表单已重置', { icon: 1 });
        }



        // 添加配件
        $('#btnAddGoods').on('click', function () {
            openGoodsSelect();
        });

        // 添加工艺流程
        $('#btnAddFlow').on('click', function () {
            openFlowSelect();
        });

        // 移除配件
        $('#btnRemoveGoods').on('click', function () {
            var checkedRows = $('#goodsBody input[type="checkbox"]:checked').closest('tr');
            if (checkedRows.length === 0) {
                layer.msg('请选择要移除的配件', { icon: 2 });
                return;
            }
            checkedRows.each(function () {
                var $tr = $(this);
                var id = $tr.data('id');
                $tr.remove();
                goodsIds = goodsIds.filter(x => x !== id);
            });
            updateGoodsIdsInput();
            refreshGoodsOrderNumbers();
            if ($('#goodsBody tr').length === 0) {
                $('#goodsBody').html('<tr><td colspan="9" style="text-align:center;color:#999;">暂无数据</td></tr>');
            }
        });

        // 移除工艺流程
        $('#btnRemoveFlow').on('click', function () {
            var checkedRows = $('#flowBody input[type="checkbox"]:checked').closest('tr');
            if (checkedRows.length === 0) {
                layer.msg('请选择要移除的工艺流程', { icon: 2 });
                return;
            }
            checkedRows.each(function () {
                var $tr = $(this);
                var id = $tr.data('id');
                $tr.remove();
                flowIds = flowIds.filter(x => x !== id);
            });
            updateFlowIdsInput();
            refreshFlowOrderNumbers();
            if ($('#flowBody tr').length === 0) {
                $('#flowBody').html('<tr><td colspan="7" style="text-align:center;color:#999;">暂无数据</td></tr>');
            }
        });



        // 打开配件选择弹窗
        function openGoodsSelect() {
            layer.open({
                type: 1,
                title: '<i class="layui-icon layui-icon-search"></i> 选择物品',
                area: ['1100px', '650px'],
                skin: 'layui-layer-molv',
                shadeClose: true,
                content: `
                    <div style="padding:25px;">
                        <!-- 搜索筛选区域 -->
                        <div class="layui-form" style="margin-bottom:20px;background:#f8f8f8;padding:20px;border-radius:5px;">
                            <div class="layui-row layui-col-space15">
                                <div class="layui-col-md4">
                                    <label style="font-weight:bold;color:#333;margin-bottom:5px;display:block;">搜索关键词</label>
                                    <input type="text" id="goodsSearchInput" placeholder="请输入物品编号/名称/规格型号" class="layui-input" style="border-radius:4px;">
                                </div>
                                <div class="layui-col-md3">
                                    <label style="font-weight:bold;color:#333;margin-bottom:5px;display:block;">物品类别</label>
                                    <select id="goodsCategorySelect" lay-filter="goodsCategory" class="layui-select" style="border-radius:4px;">
                                        <option value="">请选择物品类别</option>
                                        <option value="原材料">原材料</option>
                                        <option value="半成品">半成品</option>
                                        <option value="成品">成品</option>
                                    </select>
                                </div>
                                <div class="layui-col-md3">
                                    <label style="font-weight:bold;color:#333;margin-bottom:5px;display:block;">物品分类</label>
                                    <select id="goodsClassificationSelect" lay-filter="goodsClassification" class="layui-select" style="border-radius:4px;">
                                        <option value="">请选择物品分类</option>
                                        <option value="金属">金属</option>
                                        <option value="塑料">塑料</option>
                                        <option value="木材">木材</option>
                                        <option value="化工类">化工类</option>
                                    </select>
                                </div>
                                <div class="layui-col-md2" style="display:flex;align-items:end;">
                                    <div style="display:flex;gap:10px;">
                                        <button type="button" class="layui-btn layui-btn-sm layui-btn-normal" id="btnSearchGoods" style="border-radius:4px;">
                                            <i class="layui-icon layui-icon-search"></i> 查询
                                        </button>
                                        <button type="button" class="layui-btn layui-btn-sm layui-btn-primary" id="btnResetGoods" style="border-radius:4px;">
                                            <i class="layui-icon layui-icon-refresh"></i> 重置
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <!-- 物品列表表格 -->
                        <div style="background:#fff;border-radius:5px;overflow:hidden;box-shadow:0 2px 8px rgba(0,0,0,0.1);">
                            <table class="layui-table" lay-size="sm" id="goodsSelectTable" style="margin:0;">
                                <thead>
                                    <tr style="background:#f2f2f2;">
                                        <th style="width:50px;text-align:center;"><input type="checkbox" lay-skin="primary" lay-filter="chkAllGoodsSelect"></th>
                                        <th style="width:60px;text-align:center;">序号</th>
                                        <th style="width:120px;text-align:center;">物品编号</th>
                                        <th style="width:180px;text-align:center;">物品名称</th>
                                        <th style="width:120px;text-align:center;">规格型号</th>
                                        <th style="width:80px;text-align:center;">单位</th>
                                        <th style="width:120px;text-align:center;">物品类别</th>
                                    </tr>
                                </thead>
                                <tbody id="goodsSelectBody">
                                    <tr><td colspan="7" style="text-align:center;color:#999;padding:30px;">加载中...</td></tr>
                                </tbody>
                            </table>
                        </div>
                        
                        <!-- 分页区域 -->
                        <div id="goodsPagination" style="text-align:center;margin-top:20px;padding:15px;background:#f8f8f8;border-radius:5px;"></div>
                        
                        <!-- 操作按钮 -->
                        <div style="text-align:center;margin-top:25px;">
                            <button type="button" class="layui-btn layui-btn-primary layui-btn-lg" id="btnCancelGoods" style="margin-right:15px;border-radius:4px;">
                                <i class="layui-icon layui-icon-close"></i> 取消
                            </button>
                            <button type="button" class="layui-btn layui-btn-normal layui-btn-lg" id="btnConfirmGoods" style="border-radius:4px;">
                                <i class="layui-icon layui-icon-ok"></i> 确定
                            </button>
                        </div>
                    </div>
                `,
                success: function(layero, index) {
                    // 重新渲染表单元素
                    layui.form.render();
                    
                    // 绑定事件
                    bindGoodsSelectEvents(index);
                    
                    // 加载物品数据
                    loadGoodsData();
                }
            });
        }

        // 打开工艺流程选择弹窗
        function openFlowSelect() {
            layer.open({
                type: 1,
                title: '<i class="layui-icon layui-icon-set"></i> 添加工艺路线',
                area: ['1000px', '600px'],
                skin: 'layui-layer-molv',
                shadeClose: true,
                content: `
                    <div style="padding:25px;">
                        <!-- 搜索区域 -->
                        <div class="layui-form" style="margin-bottom:20px;background:#f8f8f8;padding:20px;border-radius:5px;">
                            <div class="layui-row layui-col-space15">
                                <div class="layui-col-md4">
                                    <label style="font-weight:bold;color:#333;margin-bottom:5px;display:block;">搜索关键词</label>
                                    <input type="text" id="flowSearchInput" placeholder="请搜索工艺流程" class="layui-input" style="border-radius:4px;">
                                </div>
                                <div class="layui-col-md4">
                                    <span id="selectedFlowCount" style="color:#5FB878;font-weight:bold;line-height:38px;">已勾选0项</span>
                                </div>
                                <div class="layui-col-md4" style="display:flex;align-items:end;justify-content:flex-end;">
                                    <div style="display:flex;gap:10px;">
                                        <button type="button" class="layui-btn layui-btn-sm layui-btn-normal" id="btnSearchFlow" style="border-radius:4px;">
                                            <i class="layui-icon layui-icon-search"></i> 查询
                                        </button>
                                        <button type="button" class="layui-btn layui-btn-sm layui-btn-primary" id="btnResetFlow" style="border-radius:4px;">
                                            <i class="layui-icon layui-icon-refresh"></i> 重置
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <!-- 工艺流程列表表格 -->
                        <div style="background:#fff;border-radius:5px;overflow:hidden;box-shadow:0 2px 8px rgba(0,0,0,0.1);">
                            <table class="layui-table" lay-size="sm" id="flowSelectTable" style="margin:0;">
                                <thead>
                                    <tr style="background:#f2f2f2;">
                                        <th style="width:50px;text-align:center;"><input type="checkbox" lay-skin="primary" lay-filter="chkAllFlowSelect"></th>
                                        <th style="width:60px;text-align:center;">序号</th>
                                        <th style="width:120px;text-align:center;">工艺流程编号</th>
                                        <th style="width:180px;text-align:center;">工艺流程名称</th>
                                        <th style="width:100px;text-align:center;">工序数量</th>
                                        <th style="width:120px;text-align:center;">负责人</th>
                                        <th style="width:120px;text-align:center;">部门</th>
                                    </tr>
                                </thead>
                                <tbody id="flowSelectBody">
                                    <tr><td colspan="7" style="text-align:center;color:#999;padding:30px;">加载中...</td></tr>
                                </tbody>
                            </table>
                        </div>
                        
                        <!-- 分页区域 -->
                        <div id="flowPagination" style="text-align:center;margin-top:20px;padding:15px;background:#f8f8f8;border-radius:5px;"></div>
                        
                        <!-- 操作按钮 -->
                        <div style="text-align:center;margin-top:25px;">
                            <button type="button" class="layui-btn layui-btn-primary layui-btn-lg" id="btnCancelFlow" style="margin-right:15px;border-radius:4px;">
                                <i class="layui-icon layui-icon-close"></i> 取消
                            </button>
                            <button type="button" class="layui-btn layui-btn-normal layui-btn-lg" id="btnConfirmFlow" style="border-radius:4px;">
                                <i class="layui-icon layui-icon-ok"></i> 确定
                            </button>
                        </div>
                    </div>
                `,
                success: function(layero, index) {
                    // 重新渲染表单元素
                    layui.form.render();
                    
                    // 绑定事件
                    bindFlowSelectEvents(index);
                    
                    // 加载工艺流程数据
                    loadFlowData();
                }
            });
        }

        // 统一刷新配件表格的序号列
        function refreshGoodsOrderNumbers() {
            $('#goodsBody tr').each(function (idx) {
                var num = idx + 1;
                $(this).children('td').eq(1).text(num);
            });
        }

        // 统一刷新工艺流程表格的序号列
        function refreshFlowOrderNumbers() {
            $('#flowBody tr').each(function (idx) {
                var num = idx + 1;
                $(this).children('td').eq(1).text(num);
            });
        }

        // 验证表单
        function validateForm() {
            // 验证必填字段
            var bomCode = $('input[name="bomCode"]').val().trim();
            var bomTitle = $('input[name="bomTitle"]').val().trim();
            var version = $('input[name="version"]').val().trim();
            var productsName = $('input[name="productsName"]').val().trim();
            var productsCode = $('input[name="productsCode"]').val().trim();
            var productsModel = $('input[name="productsModel"]').val().trim();
            var productsUnit = $('input[name="productsUnit"]').val().trim();

            if (!bomCode) {
                layer.msg('请输入BOM编号', { icon: 2 });
                $('input[name="bomCode"]').focus();
                return false;
            }

            if (!bomTitle) {
                layer.msg('请输入BOM主题', { icon: 2 });
                $('input[name="bomTitle"]').focus();
                return false;
            }

            if (!version) {
                layer.msg('请输入版本', { icon: 2 });
                $('input[name="version"]').focus();
                return false;
            }

            if (!productsName) {
                layer.msg('请输入成品名称', { icon: 2 });
                $('input[name="productsName"]').focus();
                return false;
            }

            if (!productsCode) {
                layer.msg('请输入产品编号', { icon: 2 });
                $('input[name="productsCode"]').focus();
                return false;
            }

            if (!productsModel) {
                layer.msg('请输入规格型号', { icon: 2 });
                $('input[name="productsModel"]').focus();
                return false;
            }

            if (!productsUnit) {
                layer.msg('请输入单位', { icon: 2 });
                $('input[name="productsUnit"]').focus();
                return false;
            }

            if (goodsIds.length === 0) {
                layer.msg('请至少选择一个配件', { icon: 2 });
                return false;
            }

            if (flowIds.length === 0) {
                layer.msg('请至少选择一个工艺流程', { icon: 2 });
                return false;
            }

            // 验证配件数量是否合理
            var hasInvalidQuantity = false;
            $('#goodsBody tr').each(function () {
                var $tr = $(this);
                var id = $tr.data('id');
                if (id) {
                    var quantity = parseFloat($tr.find('td:eq(6) input[type="number"]').val()) || 0;
                    if (quantity <= 0) {
                        hasInvalidQuantity = true;
                        return false; // 跳出each循环
                    }
                }
            });
            
            if (hasInvalidQuantity) {
                layer.msg('配件数量必须大于0', { icon: 2 });
                return false;
            }

            return true;
        }

        // 提交表单
        function submitForm() {
            // 重新获取表单数据
            var bomCode = $('input[name="bomCode"]').val().trim();
            var bomTitle = $('input[name="bomTitle"]').val().trim();
            var version = $('input[name="version"]').val().trim();
            var productsName = $('input[name="productsName"]').val().trim();
            
            // 收集配件信息
            var goodsRelations = [];
            $('#goodsBody tr').each(function () {
                var $tr = $(this);
                var id = $tr.data('id');
                
                // 跳过没有ID的行（如"暂无数据"行）
                if (!id) return;
                
                // 获取配件数量和损耗率
                var quantity = $tr.find('td:eq(6) input[type="number"]').val() || 0;
                var lossRate = $tr.find('td:eq(7) input[type="number"]').val() || 0;

                goodsRelations.push({
                    goodsinfoId: id,
                    quantity: parseFloat(quantity),
                    lossRate: parseFloat(lossRate)
                });
            });

            // 收集工艺流程信息
            var flowRelations = [];
            $('#flowBody tr').each(function () {
                var $tr = $(this);
                var id = $tr.data('id');
                
                // 跳过没有ID的行（如"暂无数据"行）
                if (!id) return;
                
                // 获取备注信息
                var remark = $tr.find('td:eq(5) input[type="text"]').val().trim() || '';

                flowRelations.push({
                    processFlowId: id,
                    remark: remark
                });
            });

            // 构建提交数据
            var request = {
                bomCode: bomCode,
                bomTitle: bomTitle,
                productsName: productsName,
                version: version,
                productsCode: $('input[name="productsCode"]').val().trim(),
                productsModel: $('input[name="productsModel"]').val().trim(),
                productsUnit: $('input[name="productsUnit"]').val().trim(),
                brand: $('input[name="brand"]').val().trim(),
                status: $('input[name="status"]').is(':checked'),
                output: parseInt($('input[name="output"]').val()) || 0,
                desc: $('textarea[name="desc"]').val().trim(),
                goodsRelations: goodsRelations,
                flowRelations: flowRelations
            };

            // 调试信息
            console.log('提交的BOM数据:', request);
            console.log('配件关系数据:', goodsRelations);
            console.log('工艺流程关系数据:', flowRelations);

            // 显示提交中状态
            var $btn = $('#btnSave');
            var originalText = $btn.text();
            $btn.prop('disabled', true).text('提交中...');

            // 提交到后端API
            $.ajax({
                url: 'http://localhost:5141/api/Bom/CreateBom',
                type: 'POST',
                data: JSON.stringify(request),
                contentType: 'application/json',
                success: function (res) {
                    $btn.prop('disabled', false).text(originalText);

                    if (res && res.code === 200 && res.data > 0) {
                        // 显示成功信息并跳转
                        var successIndex = layer.alert(`BOM创建成功！<br/><br/>BOM编号: ${bomCode}<br/>BOM主题: ${bomTitle}<br/>版本: ${version}`, {
                            icon: 1,
                            title: '创建成功',
                            btn: ['确定'],
                            closeBtn: 1, // 显示关闭按钮
                            shadeClose: true, // 点击遮罩关闭
                            time: 0, // 不自动关闭
                            yes: function(index) {
                                // 关闭弹窗
                                layer.close(index);
                                // 成功后跳转到BOM列表页面
                                if (window.parent && window.parent.loadPage) {
                                    window.parent.loadPage('/Bom/BomList', 'BOM管理');
                                } else {
                                    location.href = '/Bom/BomList';
                                }
                            },
                            cancel: function(index) {
                                // 点击关闭按钮或ESC键时的处理
                                layer.close(index);
                                // 同样跳转到BOM列表页面
                                if (window.parent && window.parent.loadPage) {
                                    window.parent.loadPage('/Bom/BomList', 'BOM管理');
                                } else {
                                    location.href = '/Bom/BomList';
                                }
                            }
                        });
                        
                        // 添加超时自动关闭保护机制（10秒后自动关闭）
                        setTimeout(function() {
                            if (successIndex && layer.getChildFrame) {
                                try {
                                    layer.close(successIndex);
                                    // 超时后自动跳转
                                    if (window.parent && window.parent.loadPage) {
                                        window.parent.loadPage('/Bom/BomList', 'BOM管理');
                                    } else {
                                        location.href = '/Bom/BomList';
                                    }
                                } catch(e) {
                                    console.log('弹窗已关闭');
                                }
                            }
                        }, 10000);
                    } else {
                        var errorMsg = res && res.message ? res.message : '创建失败，请重试';
                        layer.msg(errorMsg, { icon: 2 });
                    }
                },
                error: function (xhr, status, error) {
                    $btn.prop('disabled', false).text(originalText);
                    console.error('请求失败:', error);
                    layer.msg('网络请求失败，请检查网络连接', { icon: 2 });
                }
            });
        }

        // 绑定物品选择弹窗事件
        function bindGoodsSelectEvents(index) {
            // 查询按钮
            $('#btnSearchGoods').on('click', function() {
                loadGoodsData();
            });
            
            // 重置按钮
            $('#btnResetGoods').on('click', function() {
                $('#goodsSearchInput').val('');
                $('#goodsCategorySelect').val('');
                $('#goodsClassificationSelect').val('');
                layui.form.render('select');
                loadGoodsData();
            });
            
            // 全选/取消全选
            layui.form.on('checkbox(chkAllGoodsSelect)', function(data) {
                $('#goodsSelectBody input[type="checkbox"]').prop('checked', data.elem.checked);
                layui.form.render('checkbox');
            });
            
            // 确定按钮
            $('#btnConfirmGoods').on('click', function() {
                var selectedGoods = [];
                $('#goodsSelectBody input[type="checkbox"]:checked').each(function() {
                    var $tr = $(this).closest('tr');
                    selectedGoods.push({
                        id: $tr.data('id'),
                        goodsCode: $tr.find('td:eq(2)').text().trim(),
                        goodsName: $tr.find('td:eq(3)').text().trim(),
                        goodsModel: $tr.find('td:eq(4)').text().trim(),
                        unit: $tr.find('td:eq(5)').text().trim(),
                        goodsType: $tr.find('td:eq(6)').text().trim(),
                        goodsClassification: $tr.find('td:eq(6)').text().trim()
                    });
                });
                
                if (selectedGoods.length === 0) {
                    layer.msg('请选择至少一个物品', { icon: 2 });
                    return;
                }
                
                addGoodsToTable(selectedGoods);
                layer.close(index);
            });
            
            // 取消按钮
            $('#btnCancelGoods').on('click', function() {
                layer.close(index);
            });
        }

        // 绑定工艺流程选择弹窗事件
        function bindFlowSelectEvents(index) {
            // 查询按钮
            $('#btnSearchFlow').on('click', function() {
                loadFlowData();
            });
            
            // 重置按钮
            $('#btnResetFlow').on('click', function() {
                $('#flowSearchInput').val('');
                loadFlowData();
            });
            
            // 全选/取消全选
            layui.form.on('checkbox(chkAllFlowSelect)', function(data) {
                $('#flowSelectBody input[type="checkbox"]').prop('checked', data.elem.checked);
                layui.form.render('checkbox');
                updateSelectedFlowCount();
            });
            
            // 单个复选框变化
            $(document).on('change', '#flowSelectBody input[type="checkbox"]', function() {
                updateSelectedFlowCount();
            });
            
            // 确定按钮
            $('#btnConfirmFlow').on('click', function() {
                var selectedFlows = [];
                $('#flowSelectBody input[type="checkbox"]:checked').each(function() {
                    var $tr = $(this).closest('tr');
                    selectedFlows.push({
                        id: $tr.data('id'),
                        flowCode: $tr.find('td:eq(2)').text().trim(),
                        flowName: $tr.find('td:eq(3)').text().trim(),
                        flowNumber: $tr.find('td:eq(4)').text().trim(),
                        responsible: $tr.find('td:eq(5)').text().trim(),
                        department: $tr.find('td:eq(6)').text().trim()
                    });
                });
                
                if (selectedFlows.length === 0) {
                    layer.msg('请选择至少一个工艺流程', { icon: 2 });
                    return;
                }
                
                addFlowToTable(selectedFlows);
                layer.close(index);
            });
            
            // 取消按钮
            $('#btnCancelFlow').on('click', function() {
                layer.close(index);
            });
        }

        // 加载物品数据
        function loadGoodsData(page = 1, pageSize = 10) {
            var searchText = $('#goodsSearchInput').val();
            var category = $('#goodsCategorySelect').val();
            var classification = $('#goodsClassificationSelect').val();
            
            // 构建查询参数
            var params = {
                pageIndex: page,
                pageSize: pageSize
            };
            
            if (searchText) {
                params.searchText = searchText;
            }
            if (category) {
                params.goodsType = category;
            }
            if (classification) {
                params.goodsClassification = classification;
            }
            
            // 显示加载状态
            $('#goodsSelectBody').html('<tr><td colspan="7" style="text-align:center;color:#999;">加载中...</td></tr>');
            
            // 调用API获取物品数据
            $.ajax({
                url: 'http://localhost:5141/api/Goods/GetGoodsinfo',
                type: 'GET',
                data: params,
                success: function(res) {
                    if (res && res.code === 200 && res.pageData) {
                        renderGoodsTable(res, page, pageSize);
                    } else {
                        var errorMsg = res ? `API返回: ${res.code} - ${res.message || '无数据'}` : 'API响应为空';
                        $('#goodsSelectBody').html(`<tr><td colspan="7" style="text-align:center;color:#999;">${errorMsg}</td></tr>`);
                    }
                },
                error: function(xhr, status, error) {
                    $('#goodsSelectBody').html('<tr><td colspan="7" style="text-align:center;color:#999;">加载失败，请重试</td></tr>');
                }
            });
        }

        // 加载工艺流程数据
        function loadFlowData(page = 1, pageSize = 10) {
            var searchText = $('#flowSearchInput').val();
            
            // 构建查询参数
            var params = {
                pageIndex: page,
                pageSize: pageSize
            };
            
            if (searchText) {
                params.searchText = searchText;
            }
            
            // 显示加载状态
            $('#flowSelectBody').html('<tr><td colspan="7" style="text-align:center;color:#999;">加载中...</td></tr>');
            
            // 调用API获取工艺流程数据
            $.ajax({
                url: 'http://localhost:5141/api/ProcessFlow/GetProcessFlow',
                type: 'GET',
                data: params,
                success: function(res) {
                    if (res && res.code === 200 && res.pageData) {
                        renderFlowTable(res, page, pageSize);
                    } else {
                        var errorMsg = res ? `API返回: ${res.code} - ${res.message || '无数据'}` : 'API响应为空';
                        $('#flowSelectBody').html(`<tr><td colspan="7" style="text-align:center;color:#999;">${errorMsg}</td></tr>`);
                    }
                },
                error: function(xhr, status, error) {
                    $('#flowSelectBody').html('<tr><td colspan="7" style="text-align:center;color:#999;">加载失败，请重试</td></tr>');
                }
            });
        }

        // 渲染物品表格
        function renderGoodsTable(data, page, pageSize) {
            var html = '';
            if (data.pageData && data.pageData.length > 0) {
                data.pageData.forEach(function(item, index) {
                    var rowNum = (page - 1) * pageSize + index + 1;
                    html += `
                        <tr data-id="${item.id || ''}" 
                            data-goodsCode="${item.goodsCode || ''}" 
                            data-goodsName="${item.goodsName || ''}" 
                            data-goodsModel="${item.goodsModel || ''}" 
                            data-unit="${item.unit || ''}" 
                            data-goodsType="${item.goodsType || ''}" 
                            data-goodsClassification="${item.goodsClassification || ''}">
                            <td><input type="checkbox" lay-skin="primary"></td>
                            <td>${rowNum}</td>
                            <td>${item.goodsCode || ''}</td>
                            <td>${item.goodsName || ''}</td>
                            <td>${item.goodsModel || ''}</td>
                            <td>${item.unit || ''}</td>
                            <td>${item.goodsType || ''}</td>
                        </tr>
                    `;
                });
            } else {
                html = '<tr><td colspan="7" style="text-align:center;color:#999;">暂无数据</td></tr>';
            }
            
            $('#goodsSelectBody').html(html);
            renderGoodsPagination(data.totalCount, pageSize, page);
            layui.form.render('checkbox');
        }

        // 渲染工艺流程表格
        function renderFlowTable(data, page, pageSize) {
            var html = '';
            if (data.pageData && data.pageData.length > 0) {
                data.pageData.forEach(function(item, index) {
                    var rowNum = (page - 1) * pageSize + index + 1;
                    html += `
                        <tr data-id="${item.id || ''}" 
                            data-flowCode="${item.flowCode || ''}" 
                            data-flowName="${item.flowName || ''}" 
                            data-flowNumber="${item.flowNumber || ''}" 
                            data-responsible="${item.responsible || ''}" 
                            data-department="${item.department || ''}">
                            <td><input type="checkbox" lay-skin="primary"></td>
                            <td>${rowNum}</td>
                            <td>${item.flowCode || ''}</td>
                            <td>${item.flowName || ''}</td>
                            <td>${item.flowNumber || ''}</td>
                            <td>${item.responsible || ''}</td>
                            <td>${item.department || ''}</td>
                        </tr>
                    `;
                });
            } else {
                html = '<tr><td colspan="7" style="text-align:center;color:#999;">暂无数据</td></tr>';
            }
            
            $('#flowSelectBody').html(html);
            renderFlowPagination(data.totalCount, pageSize, page);
            layui.form.render('checkbox');
            updateSelectedFlowCount();
        }

        // 渲染物品分页
        function renderGoodsPagination(total, pageSize, currentPage) {
            var totalPages = Math.ceil(total / pageSize);
            if (totalPages <= 1) {
                $('#goodsPagination').html('');
                return;
            }
            
            var html = `<span>共${total}项数据</span> `;
            html += `<select id="goodsPageSize" style="margin:0 10px;">`;
            html += `<option value="5" ${pageSize == 5 ? 'selected' : ''}>5条/页</option>`;
            html += `<option value="10" ${pageSize == 10 ? 'selected' : ''}>10条/页</option>`;
            html += `<option value="20" ${pageSize == 20 ? 'selected' : ''}>20条/页</option>`;
            html += `</select> `;
            
            html += `<div class="layui-box layui-laypage layui-laypage-default">`;
            if (currentPage > 1) {
                html += `<a href="javascript:;" class="layui-laypage-prev" data-page="${currentPage - 1}">上一页</a>`;
            }
            
            for (var i = 1; i <= totalPages; i++) {
                if (i === currentPage) {
                    html += `<span class="layui-laypage-curr"><em class="layui-laypage-em"></em><em>${i}</em></span>`;
                } else {
                    html += `<a href="javascript:;" data-page="${i}">${i}</a>`;
                }
            }
            
            if (currentPage < totalPages) {
                html += `<a href="javascript:;" class="layui-laypage-next" data-page="${currentPage + 1}">下一页</a>`;
            }
            html += `</div>`;
            
            $('#goodsPagination').html(html);
            
            // 绑定分页事件
            $('#goodsPagination a, #goodsPagination select').on('click change', function() {
                var page = $(this).data('page') || 1;
                var size = $('#goodsPageSize').val() || pageSize;
                loadGoodsData(page, size);
            });
        }

        // 渲染工艺流程分页
        function renderFlowPagination(total, pageSize, currentPage) {
            var totalPages = Math.ceil(total / pageSize);
            if (totalPages <= 1) {
                $('#flowPagination').html('');
                return;
            }
            
            var html = `<span>共${total}项数据</span> `;
            html += `<select id="flowPageSize" style="margin:0 10px;">`;
            html += `<option value="5" ${pageSize == 5 ? 'selected' : ''}>5条/页</option>`;
            html += `<option value="10" ${pageSize == 10 ? 'selected' : ''}>10条/页</option>`;
            html += `<option value="20" ${pageSize == 20 ? 'selected' : ''}>20条/页</option>`;
            html += `</select> `;
            
            html += `<div class="layui-box layui-laypage layui-laypage-default">`;
            if (currentPage > 1) {
                html += `<a href="javascript:;" class="layui-laypage-prev" data-page="${currentPage - 1}">上一页</a>`;
            }
            
            for (var i = 1; i <= totalPages; i++) {
                if (i === currentPage) {
                    html += `<span class="layui-laypage-curr"><em class="layui-laypage-em"></em><em>${i}</em></span>`;
                } else {
                    html += `<a href="javascript:;" data-page="${i}">${i}</a>`;
                }
            }
            
            if (currentPage < totalPages) {
                html += `<a href="javascript:;" class="layui-laypage-next" data-page="${currentPage + 1}">下一页</a>`;
            }
            html += `</div>`;
            
            $('#flowPagination').html(html);
            
            // 绑定分页事件
            $('#flowPagination a, #flowPagination select').on('click change', function() {
                var page = $(this).data('page') || 1;
                var size = $('#flowPageSize').val() || pageSize;
                loadFlowData(page, size);
            });
        }

        // 更新已选择的工艺流程数量
        function updateSelectedFlowCount() {
            var count = $('#flowSelectBody input[type="checkbox"]:checked').length;
            $('#selectedFlowCount').text('已勾选' + count + '项');
        }

        // 添加物品到主表格
        function addGoodsToTable(selectedGoods) {
            console.log('添加物品到主表格，选中的物品:', selectedGoods);
            
            selectedGoods.forEach(function(goods) {
                console.log('处理物品:', goods);
                
                // 检查是否已经添加过
                if (goodsIds.includes(goods.id)) {
                    console.log('物品已存在，跳过:', goods.id);
                    return;
                }
                
                var newRow = `
                    <tr data-id="${goods.id || ''}">
                        <td><input type="checkbox" lay-skin="primary"></td>
                        <td>${$('#goodsBody tr').length + 1}</td>
                        <td>${goods.goodsCode || ''}</td>
                        <td>${goods.goodsName || ''}</td>
                        <td>${goods.goodsModel || ''}</td>
                        <td>${goods.unit || ''}</td>
                        <td><input type="number" class="layui-input" value="1" min="0" step="0.01" style="width:80px;"></td>
                        <td><input type="number" class="layui-input" value="0" min="0" step="0.01" style="width:80px;"></td>
                        <td>
                            <button type="button" class="layui-btn layui-btn-xs layui-btn-danger" onclick="removeGoodsRow(this)">删除</button>
                        </td>
                    </tr>
                `;
                
                console.log('生成的行HTML:', newRow);
                $('#goodsBody').append(newRow);
                goodsIds.push(goods.id);
            });
            
            updateGoodsIdsInput();
            refreshGoodsOrderNumbers();
            layui.form.render();
        }

        // 添加工艺流程到主表格
        function addFlowToTable(selectedFlows) {
            console.log('添加工艺流程到主表格，选中的流程:', selectedFlows);
            
            selectedFlows.forEach(function(flow) {
                console.log('处理流程:', flow);
                
                // 检查是否已经添加过
                if (flowIds.includes(flow.id)) {
                    console.log('流程已存在，跳过:', flow.id);
                    return;
                }
                
                var newRow = `
                    <tr data-id="${flow.id || ''}">
                        <td><input type="checkbox" lay-skin="primary"></td>
                        <td>${$('#flowBody tr').length + 1}</td>
                        <td>${flow.flowCode || ''}</td>
                        <td>${flow.flowName || ''}</td>
                        <td>${flow.flowNumber || ''}</td>
                        <td><input type="text" class="layui-input" placeholder="请输入备注" style="width:100px;"></td>
                        <td>
                            <button type="button" class="layui-btn layui-btn-xs layui-btn-danger" onclick="removeFlowRow(this)">删除</button>
                        </td>
                    </tr>
                `;
                
                console.log('生成的行HTML:', newRow);
                $('#flowBody').append(newRow);
                flowIds.push(flow.id);
            });
            
            updateFlowIdsInput();
            refreshFlowOrderNumbers();
            layui.form.render();
        }

        // 删除物品行
        function removeGoodsRow(btn) {
            var $tr = $(btn).closest('tr');
            var id = $tr.data('id');
            $tr.remove();
            goodsIds = goodsIds.filter(x => x !== id);
            updateGoodsIdsInput();
            refreshGoodsOrderNumbers();
            
            if ($('#goodsBody tr').length === 0) {
                $('#goodsBody').html('<tr><td colspan="9" style="text-align:center;color:#999;">暂无数据</td></tr>');
            }
        }

        // 删除工艺流程行
        function removeFlowRow(btn) {
            var $tr = $(btn).closest('tr');
            var id = $tr.data('id');
            $tr.remove();
            flowIds = flowIds.filter(x => x !== id);
            updateFlowIdsInput();
            refreshFlowOrderNumbers();
            
            if ($('#flowBody tr').length === 0) {
                $('#flowBody').html('<tr><td colspan="7" style="text-align:center;color:#999;">暂无数据</td></tr>');
            }
        }
    });
</script>
